package com.example.myapplication;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.Preview;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.core.content.ContextCompat;

import android.widget.Toast;

import com.google.common.util.concurrent.ListenableFuture;
import com.google.mediapipe.tasks.vision.core.RunningMode;
import com.lztek.toolkit.Lztek;

import java.io.File;
import java.util.concurrent.ExecutionException;

public class MainActivity extends AppCompatActivity {
    private HandLandmarkerHelper handLandmarkerHelper;
    //高电平标记 暂时弃用private boolean isHigh = true;

    public void low(Context context) {
        Lztek lztek = Lztek.create(context);
        lztek.gpioEnable(88);
        lztek.setGpioOutputMode(88);
        lztek.setGpioValue(88, 0);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        PreviewView previewView = findViewById(R.id.preview_view);
        OverlayView overlayView = findViewById(R.id.overlay_view);
        SitReachView sitReachView = findViewById(R.id.sit_reach_view);
//        按钮方案，已经弃用
//        Button button1 = findViewById(R.id.button1);
//        Lztek lztek = Lztek.create(this);
//        lztek.gpioEnable(88);
//        lztek.setGpioOutputMode(88);
//        lztek.setGpioValue(88, 0);
//        Log.d("lztek-main", "GPIO88 初始设置为高电平");
//
//        // 按钮点击事件
//        button1.setOnClickListener(v -> {
//            if (isHigh) {
//
//                lztek.setGpioValue(88, 0);
//                Log.d("lztek-main", "GPIO88 切换为低电平");
//            } else {
//
//                lztek.setGpioValue(88, 1);
//                Log.d("lztek-main", "GPIO88 切换为高电平");
//            }
//            isHigh = !isHigh;
//        });
        overlayView.setSitReachView(sitReachView);

        float yCoordinateOfLabelZero = sitReachView.getYCoordinateOfLabelZero();
        overlayView.setYCoordinateOfLabelZero(yCoordinateOfLabelZero);

        float yCoordinateOfLabelTen = sitReachView.getYCoordinateOfLabelTen();
        overlayView.setYCoordinateOfLabelTen(yCoordinateOfLabelTen);

        float yCoordinateOfLabelTwenty = sitReachView.getYCoordinateOfLabelTwenty();
        overlayView.setYCoordinateOfLabelTwenty(yCoordinateOfLabelTwenty);

        float yCoordinateOfLabelThirty = sitReachView.getYCoordinateOfLabelThirty();
        overlayView.setYCoordinateOfLabelThirty(yCoordinateOfLabelThirty);

        float yCoordinateOfLabelForty = sitReachView.getYCoordinateOfLabelForty();
        overlayView.setYCoordinateOfLabelForty(yCoordinateOfLabelForty);

        float yCoordinateOfLabelFifty = sitReachView.getYCoordinateOfLabelFifty();
        overlayView.setYCoordinateOfLabelFifty(yCoordinateOfLabelFifty);

        float yCoordinateOfLabelSixty = sitReachView.getYCoordinateOfLabelSixty();
        overlayView.setYCoordinateOfLabelSixty(yCoordinateOfLabelSixty);

        handLandmarkerHelper = new HandLandmarkerHelper(
                HandLandmarkerHelper.DEFAULT_HAND_DETECTION_CONFIDENCE,
                HandLandmarkerHelper.DEFAULT_HAND_TRACKING_CONFIDENCE,
                HandLandmarkerHelper.DEFAULT_HAND_PRESENCE_CONFIDENCE,
                HandLandmarkerHelper.DEFAULT_NUM_HANDS,
                HandLandmarkerHelper.DELEGATE_GPU,
                RunningMode.LIVE_STREAM,
                this,
                new HandLandmarkerHelper.LandmarkerListener() {
                    @Override
                    public void onError(String error, int errorCode) {
                        runOnUiThread(() -> Toast.makeText(MainActivity.this, "Error: " + error, Toast.LENGTH_SHORT).show());
                    }
                    @Override
                    public void onResults(HandLandmarkerHelper.ResultBundle resultBundle) {
                        runOnUiThread(() -> overlayView.setResults(resultBundle.getResult().get(), resultBundle.getInputImageHeight(), resultBundle.getInputImageWidth(), RunningMode.LIVE_STREAM));
                    }
                }
        );
        startCamera(previewView);
    }

    private void startCamera(PreviewView previewView) {
        ListenableFuture<ProcessCameraProvider> cameraProviderFuture = ProcessCameraProvider.getInstance(this);

        cameraProviderFuture.addListener(() -> {
            try {
                ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
                bindPreview(cameraProvider, previewView);
            } catch (ExecutionException | InterruptedException e) {
                Toast.makeText(this, "Error starting camera: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }, ContextCompat.getMainExecutor(this));
    }

    //2021/8/15 修改接口依赖标准：camera2 to cameraX

    //优化现有代码，调试两个新摄像头，观测在现场情况下摄像头捕捉画面是没问题的，从40cm到-20cm都能进行观测，
    private void bindPreview(ProcessCameraProvider cameraProvider, PreviewView previewView) {
        Preview preview = new Preview.Builder().build();
        CameraSelector cameraSelector = new CameraSelector.Builder()
                .requireLensFacing(CameraSelector.LENS_FACING_BACK)
                .build();
        ImageAnalysis imageAnalysis = new ImageAnalysis.Builder()
                .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
                .build();
        imageAnalysis.setAnalyzer(ContextCompat.getMainExecutor(this), imageProxy -> {
            handLandmarkerHelper.detectLiveStream(imageProxy, true);
        });
        preview.setSurfaceProvider(previewView.getSurfaceProvider());
        cameraProvider.bindToLifecycle(this, cameraSelector, preview, imageAnalysis);
    }

}
